package cn.iocoder.yudao.module.xiaoBizHandler.service.attach;

import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.framework.common.genId.PKGenerator;
import cn.iocoder.yudao.module.system.framework.attach.config.AttachProperties;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.xiaoBizHandler.controller.admin.attach.vo.AttachCreateReqVO;
import cn.iocoder.yudao.module.xiaoBizHandler.controller.admin.attach.vo.AttachUpdateReqVO;
import cn.iocoder.yudao.module.xiaoBizHandler.convert.attach.AttachConvert;
import cn.iocoder.yudao.module.xiaoBizHandler.dal.dataobject.attach.AttachDO;
import cn.iocoder.yudao.module.xiaoBizHandler.dal.mysql.attach.AttachMapper;
import cn.iocoder.yudao.module.xiaoBizHandler.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.StandardCopyOption;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.xiaoBizHandler.enums.ErrorCodeConstants.X_TB_ATTACH_NOT_EXISTS;

@Service
@Validated
public class AttachServiceImpl implements AttachService {

    @Resource
    AttachMapper attachMapper;

    @Resource
    AttachProperties attachProperties;

    @Resource
    private AdminUserService adminUserService;


    @Override
    public String createAttach(AttachCreateReqVO createReqVO) {
        // 插入
        AttachDO attach = AttachConvert.INSTANCE.convert(createReqVO);
        attach.setId(PKGenerator.newId());
        attachMapper.insert(attach);
        // 返回主键id
        return attach.getId();
    }

    private void validateAttachExists(String id) {
        if (attachMapper.selectById(id) == null) {
            throw exception(X_TB_ATTACH_NOT_EXISTS);
        }
    }

    @Override
    public void updateAttach(AttachUpdateReqVO updateReqVO) {
        // 校验数据库中 X_TB_ATTACH 表是否存在
        this.validateAttachExists(updateReqVO.getId());
        // 更新
        AttachDO updateObj = AttachConvert.INSTANCE.convert(updateReqVO);
        attachMapper.updateById(updateObj);
    }

    @Override
    public void deleteAttach(String id) {
        // 校验数据库中 X_TB_ATTACH 表是否存在
        this.validateAttachExists(id);
        // 删除文件
        // todo: 这里暂时不删除文件，数据也是逻辑删除
        String attachPath = getAttachPath(id);
//        FileUtil.del(attachPath);
        // 删除
        attachMapper.deleteById(id);

    }

    @Override
    public AttachDO getAttach(String id) {
        return attachMapper.selectById(id);
    }

    @Override
    public List<AttachDO> getAttachList(Collection<String> ids) {
        return attachMapper.selectBatchIds(ids);
    }

    @Override
    public AttachDO uploadAttach(MultipartFile file) {
        Calendar cal = Calendar.getInstance();
        int y = cal.get(Calendar.YEAR);
        int m = cal.get(Calendar.MONTH) + 1;
        int d = cal.get(Calendar.DATE);
        int h = cal.get(Calendar.HOUR_OF_DAY);
        int mi = cal.get(Calendar.MINUTE);
        String originalFilename = file.getOriginalFilename();
        String basePath = attachProperties.getPath();  // 比如 "E:/ruoyi/attach/"
        String suffix = FileUtils.getSuffix(originalFilename);
        String relativePath = y + "/" + m + "/" + d + "/" + h + "/" + mi + "/";
        String id = PKGenerator.newId();
        String attachPath = basePath + relativePath + id + "." + suffix;


        File attach = FileUtil.touch(attachPath);
        AttachDO bean = null;
        try {
            byte[] bytes = file.getBytes();
            FileUtil.writeBytes(bytes, attach);

//            adminAuthService.refreshTenantIdIfAbsent();
            bean = AttachDO.builder()
                    .id(id)
                    .attachName(FileUtil.mainName(originalFilename))
                    .attachSuffix("."+suffix)
//                    .attachOwnerId(adminAuthService.getContextLoginUser().getId().toString())
                    .attachPath(relativePath)
                    .attachType(suffix)
                    .attachSize(BigDecimal.valueOf(file.getSize()))
                    .lastTime(BigDecimal.valueOf(System.currentTimeMillis()))
                    .nowYear(BigDecimal.valueOf(y))
                    .isCopy(0)
//                    .tenantId(tenantId.toString())
                    .build();
            attachMapper.insert(bean);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bean;
    }

    @Override
    public String getAttachPath(String id) {
        String attachAbsolutePath = "";
        AttachDO attach = getAttach(id);
        String basePath = attachProperties.getPath();
        attachAbsolutePath = basePath + attach.getAttachPath() + attach.getId() + attach.getAttachSuffix();
        return attachAbsolutePath;
    }

    /**
     * 页面点击保存后，刷新附件信息
     * @param id
     * @param attachName
     * @param pageId
     */
    @Override
    public void refreshAttach(String id, String attachName, String pageId) {
        // 校验数据库中 X_TB_ATTACH 表是否存在
        this.validateAttachExists(id);
        AttachDO attach = attachMapper.selectById(id);
        if (attach == null) return;
        attach.setAttachName(attachName);
        attach.setReferId(pageId);
        attachMapper.updateById(attach);
    }


    /**
     * 新增附件，并复制文件
     * @param attachName    文件名，比如：test
     * @param pageId        页面主键id
     * @param xmindTmpFilePath  模板文件绝对路径
     * @return  attachDO
     */
    public AttachDO createAttach(String attachName, String pageId, String xmindTmpFilePath) {
        Calendar cal = Calendar.getInstance();
        int y = cal.get(Calendar.YEAR);
        int m = cal.get(Calendar.MONTH) + 1;
        int d = cal.get(Calendar.DATE);
        int h = cal.get(Calendar.HOUR_OF_DAY);
        int mi = cal.get(Calendar.MINUTE);
        String basePath = attachProperties.getPath();  // 比如 "E:/ruoyi/attach/"
        String suffix = FileUtils.getSuffix(xmindTmpFilePath);
        String relativePath = y + "/" + m + "/" + d + "/" + h + "/" + mi + "/";
        String id = PKGenerator.newId();
        String attachPath = basePath + relativePath + id + "." + suffix;


        File file = FileUtil.copyFile(xmindTmpFilePath, attachPath, StandardCopyOption.COPY_ATTRIBUTES);

//        adminAuthService.refreshTenantIdIfAbsent();
        AttachDO attach = AttachDO.builder()
                .id(id)
                .referId(pageId)
                .attachName(attachName)
                .attachSuffix("."+suffix)
                .attachOwnerId("")
                .attachPath(relativePath)
                .attachType(suffix)
                .attachSize(BigDecimal.valueOf(FileUtil.size(file)))
                .lastTime(BigDecimal.valueOf(System.currentTimeMillis()))
                .nowYear(BigDecimal.valueOf(y))
                .isCopy(0)
                .build();
        attachMapper.insert(attach);
        return attach;
    }


}
